'''
Author: bodhi
Date: 2025-05-09 11:05:50
LastEditors: bodhi
LastEditTime: 2025-07-17 08:25:41
FilePath: \wordproc\src\main.py
'''
import os
import sys
from pathlib import Path
from datetime import datetime
from tqdm import tqdm
import json
import logging

# 完全禁用根日志记录器
root_logger = logging.getLogger()
root_logger.handlers = []
root_logger.propagate = False
root_logger.disabled = True

from processors.doc_process import DocumentProcessor
from utils.file_utils import setup_output_directory
from utils.excel_recorder import ExcelRecorder

def main(comment_author, required_sections):
    if len(sys.argv) != 3:
        print("Usage: python main.py <input_directory> <output_directory>")
        sys.exit(1)

    input_dir = Path(sys.argv[1])
    output_dir = Path(sys.argv[2]).resolve()  # 确保是绝对路径

    # 创建日志目录
    logs_dir = output_dir / "logs"
    logs_dir.mkdir(exist_ok=True)

    # 创建主日志记录器  
    main_logger = logging.getLogger('main')
    main_logger.setLevel(logging.INFO)
    main_logger.handlers = []
    main_logger.propagate = False

    # 主日志文件
    main_log_file = logs_dir / f'main_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
    main_handler = logging.FileHandler(str(main_log_file.absolute()), encoding='utf-8', mode='w')
    main_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
    main_logger.addHandler(main_handler)

    main_logger.info(f"Starting homework grading process")
    main_logger.info(f"Input directory: {input_dir}")
    main_logger.info(f"Output directory: {output_dir}")

    # Create output directory structure
    setup_output_directory(output_dir)

    # Initialize document grader
    grader = DocumentProcessor()
    
    # Initialize Excel recorder
    excel_recorder = ExcelRecorder(output_dir, main_logger)

    # Process all documents
    doc_files = list(input_dir.glob("*.doc*"))
    for doc_file in tqdm(doc_files, desc="Processing documents"):
        try:
            # 为每个文档创建独立的日志文件
            doc_name = doc_file.stem
            doc_log_file = logs_dir / f"{doc_name}.log"
            
            # 创建新的日志记录器
            doc_logger = logging.getLogger(f'doc_{doc_name}')
            doc_logger.setLevel(logging.INFO)
            doc_logger.handlers = []
            doc_logger.propagate = False
            
            # 创建文件处理器，使用绝对路径
            doc_handler = logging.FileHandler(str(doc_log_file.absolute()), encoding='utf-8', mode='w')
            doc_handler.setFormatter(logging.Formatter('%(message)s'))
            doc_logger.addHandler(doc_handler)

            try:
                # Extract student ID and name from filename
                filename = doc_file.stem
                student_id = filename.split('_')[0].split('-')[0].split(' ')[0]
                student_name = filename.split('_', 1)[1] if '_' in filename else ''

                # 设置文档评分器的日志记录器
                grader.set_logger(doc_logger)

                # Grade the document
                result = grader.grade_document(doc_file, student_id, student_name, required_sections)
                
                # Add result to Excel recorder
                excel_recorder.add_result(
                    student_id=result['student_id'],
                    student_name=result['student_name'],
                    score=result['score'],
                    comments=result['comments']
                )
                
                # Save results
                output_file = output_dir / f"{filename}.docx"
                grader.save_results(result['comment_text'], output_file, doc_file, comment_author)
                
                doc_logger.info(f"成功处理文档: {filename}")
            except Exception as e:
                doc_logger.error(f"处理文档时发生错误: {str(e)}")
                raise
            finally:
                # 清理日志处理器
                doc_handler.close()
                doc_logger.removeHandler(doc_handler)
                # 删除日志记录器
                logging.getLogger().manager.loggerDict.pop(f'doc_{doc_name}', None)
                # 清除文档评分器的日志记录器
                grader.set_logger(None)
        except Exception as e:
            main_logger.error(f"Error processing {doc_file.name}: {str(e)}")

    # Save Excel results
    excel_recorder.save_to_excel()
    
    # Get and log statistics
    stats = excel_recorder.get_statistics()
    main_logger.info("\n============ 评分统计信息 ============")
    main_logger.info(f"总学生数: {stats['total_students']}")
    main_logger.info(f"平均分: {stats['average_score']}")
    main_logger.info(f"最高分: {stats['highest_score']}")
    main_logger.info(f"最低分: {stats['lowest_score']}")
    main_logger.info("分数分布:")
    for score_range, count in stats['score_distribution'].items():
        main_logger.info(f"  {score_range}分: {count}人")
    main_logger.info("=====================================")
    
    main_logger.info("Homework grading process completed")

if __name__ == "__main__":
    if len(sys.argv) == 1:
        # 从配置文件中读取参数
        with open('src/config.json', 'r', encoding='utf-8') as config_file:
            config = json.load(config_file)
        
        # 确保输出目录路径是绝对路径
        output_dir = Path(config['output_directory']).resolve()
        input_dir = Path(config['input_directory']).resolve()
        
        sys.argv.extend([
            str(input_dir),  # 作业目录
            str(output_dir)  # 输出目录
        ])
        comment_author = config['comment_author']
        
        required_sections = config['required_sections']
    main(comment_author, required_sections) 